export class DigestUtils {

  private static textEncode(value: string): Uint8Array {
    const utf8 = unescape(encodeURIComponent(value));
    const result = new Uint8Array(utf8.length);
    for (let i = 0; i < utf8.length; i++) {
      result[i] = utf8.charCodeAt(i);
    }
    return result;
  }

  static async sha256(data: string): Promise<string> {
    const encodeData = DigestUtils.textEncode(data);
    let res = '';

    const result = await crypto.subtle.digest("SHA-256", encodeData);
    const bytes = new Uint8Array(result);
    for (let i = 0; i < bytes.length; i++) {
      let byte = bytes[i].toString(16);
      byte = (byte.length < 2) ? ('0' + byte) : byte;
      res += byte;
    }

    return res.toUpperCase();
  }

}
